package main

import (
	"github.com/gin-gonic/gin"
	"net"
	"net/http"
	_ "net/http/pprof"
	"new-pk01/cfg"
	"strings"
	"time"
)

func UrlToString(s *cfg.Monitor) string {
	var res string
	for _, v := range s.MarPf {
		res += v
	}
	return res
}

func DetectDomain(host string, isHttps string, timeout int) (string, int) {
	var networks string
	if isHttps == "1" {
		networks = "https"
	} else {
		networks = "http"
	}
	Address := host + ":" + networks
	conn, err := net.DialTimeout("tcp", Address, time.Second*time.Duration(timeout))
	if err != nil {
		return "nil", http.StatusBadRequest
	} else {
		ip := strings.Split(conn.RemoteAddr().String(), ":")[0]
		conn.Close()
		return ip, http.StatusOK
	}
}

func main() {
	r := gin.Default()

	filePath := "config/config.yaml"
	Instance := cfg.ReadYamlCfg(filePath)
	r.GET("/probe/http", func(c *gin.Context) {
		host := c.Query("host")
		isHttps := c.DefaultQuery("is_https", "1")
		startTime := time.Now().UnixNano() / 1e6
		RemoteIp, code := DetectDomain(host, isHttps, Instance.DialTimeOut.Timeout)
		endTime := time.Now().UnixNano() / 1e6
		intervalTime := endTime - startTime
		c.JSON(code, gin.H{
			"RemoteIp":    RemoteIp,
			"status_code": code,
			"timeout(ms)": intervalTime,
		})
	})

	//go func() {
	//	http.ListenAndServe("0.0.0.0:18080", nil)
	//}()

	urls, ok := cfg.ReadJsonCfg()
	if !ok {
		return
	}
	r.GET("/help", func(h *gin.Context) {
		h.String(200, UrlToString(urls))
	})

	Addr := Instance.ServerListen.Ip + ":" + Instance.ServerListen.Port
	r.Run(Addr)
}
